package cn.edu.scau.cmi.wuzhenxin.hibernate.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.edu.scau.cmi.wuzhenxin.hibernate.domain.Teacher;

public class TeacherDAOByHibernate extends BaseHibernateDao{

	private static final Logger log = LoggerFactory.getLogger(TeacherDAOByHibernate.class);
	// property constants
	public static final String NAME = "name";
	
	private Session session = getSession();
	
	public Teacher findById(Integer id) {
		log.debug("getting Teacher instance with id: " + id);
		try {
			Teacher instance = (Teacher) session.get(
					"cn.edu.scau.cmi.wuzhenxin.hibernate.domain.Teacher", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}
	
	public boolean save(Teacher teacher) {
		log.debug("saving teacher instance");
		try {
			Transaction transaction = session.beginTransaction();
			session.save(teacher);
			transaction.commit();
			log.debug("save successful");
			return true;
		} catch (RuntimeException re) {
			re.printStackTrace();
			throw re;
		}
	}
	
	public List<Teacher> findAll(){
		log.debug("getting all Teacher instance");
		try {
			String queryString = "from Teacher";
			Query queryObject = session.createQuery(queryString);
			log.debug("get all teacher successful");
			List<Teacher> list = queryObject.list();
			return list;
		} catch (RuntimeException re) {
			log.error("get all teacher failed", re);
			throw re;
		} 
	}
	
	public boolean updateById(Teacher teacher) {
		log.debug("update Teacher instance with id =#"+teacher.getId());
		try {
			Transaction transaction = session.beginTransaction();
			session.saveOrUpdate(teacher);
			transaction.commit();
			log.debug("update teacher  successful");
			return true;
		} catch (RuntimeException re) {
			log.error("update teacher failed", re);
			throw re;
		} 
	}
	
	public boolean deleteById(Teacher teacher) {
		log.debug("delete Teacher instance with id =#"+teacher.getId());
		try {
			Transaction transaction = session.beginTransaction();
			session.delete(teacher);
			transaction.commit();
			log.debug("delete teacher successful");
			return true;
		} catch (RuntimeException re) {
			log.error("delete teacher failed", re);
			throw re;
		}
	}
}
